<template>
  <a-modal
    v-model:open="visible"
    title="导出对话记录"
    :confirm-loading="exporting"
    @ok="handleExport"
    @cancel="handleCancel"
    width="500px"
  >
    <div class="export-form">
      <a-form :model="exportForm" layout="vertical">
        <a-form-item label="导出格式">
          <a-select v-model:value="exportForm.format" disabled>
            <a-select-option value="markdown">Markdown (.md)</a-select-option>
          </a-select>
        </a-form-item>

        <a-form-item label="时间范围" help="不选择时间范围将导出全部对话记录">
          <a-space direction="vertical" style="width: 100%">
            <div>
              <label>开始时间：</label>
              <a-date-picker
                v-model:value="exportForm.startTime"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择开始时间"
                style="width: 100%; margin-top: 4px"
              />
            </div>
            <div>
              <label>结束时间：</label>
              <a-date-picker
                v-model:value="exportForm.endTime"
                show-time
                format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择结束时间"
                style="width: 100%; margin-top: 4px"
              />
            </div>
          </a-space>
        </a-form-item>

        <a-form-item>
          <a-alert
            message="导出说明"
            description="导出的文件将包含指定时间范围内的所有对话记录，包括用户消息和AI回复。文件格式为Markdown，可以用任何文本编辑器打开。"
            type="info"
            show-icon
          />
        </a-form-item>
      </a-form>
    </div>

    <template #footer>
      <a-space>
        <a-button @click="handleCancel">取消</a-button>
        <a-button @click="handleQuickExport" :loading="exporting">
          <DownloadOutlined />
          快速导出全部
        </a-button>
        <a-button type="primary" @click="handleExport" :loading="exporting">
          <DownloadOutlined />
          导出
        </a-button>
      </a-space>
    </template>
  </a-modal>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue'
import { message } from 'ant-design-vue'
import { DownloadOutlined } from '@ant-design/icons-vue'
import { exportChatHistory } from '@/api/chatHistoryController'
import type { Dayjs } from 'dayjs'

interface Props {
  appId: string
  appName?: string
}

interface Emits {
  (e: 'update:open', value: boolean): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 控制弹窗显示
const visible = defineModel<boolean>('open', { default: false })

// 导出表单
const exportForm = reactive({
  format: 'markdown',
  startTime: undefined as Dayjs | undefined,
  endTime: undefined as Dayjs | undefined
})

// 导出状态
const exporting = ref(false)

// 处理导出
const handleExport = async () => {
  await performExport(false)
}

// 快速导出全部
const handleQuickExport = async () => {
  await performExport(true)
}

// 执行导出
const performExport = async (isQuickExport: boolean = false) => {
  try {
    exporting.value = true

    // 构建导出参数
    const params: API.exportChatHistoryParams = {
      appId: props.appId
    }

    // 如果不是快速导出，则添加时间范围参数
    if (!isQuickExport) {
      if (exportForm.startTime) {
        params.startTime = exportForm.startTime.format('YYYY-MM-DD HH:mm:ss')
      }
      if (exportForm.endTime) {
        params.endTime = exportForm.endTime.format('YYYY-MM-DD HH:mm:ss')
      }

      // 验证时间范围
      if (
        exportForm.startTime &&
        exportForm.endTime &&
        exportForm.startTime.isAfter(exportForm.endTime)
      ) {
        message.error('开始时间不能晚于结束时间')
        return
      }
    }

    // 调用导出接口
    const response = (await exportChatHistory(params, {
      responseType: 'blob'
    })) as unknown as { data: Blob }

    // 创建下载链接
    const blob = new Blob([response.data], { type: 'text/markdown; charset=UTF-8' })
    const url = URL.createObjectURL(blob)

    // 生成文件名
    const timestamp = new Date().toISOString().replace(/[:.]/g, '-').slice(0, 19)
    const appNamePart = props.appName ? `_${props.appName}` : ''
    const timeRangePart =
      !isQuickExport && (exportForm.startTime || exportForm.endTime)
        ? `_${exportForm.startTime?.format('YYYYMMDD') || 'start'}_${
            exportForm.endTime?.format('YYYYMMDD') || 'end'
          }`
        : ''
    const fileName = `chat_history_app_${props.appId}${appNamePart}${timeRangePart}_${timestamp}.md`

    // 创建下载链接并触发下载
    const link = document.createElement('a')
    link.href = url
    link.download = fileName
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)

    // 清理URL对象
    URL.revokeObjectURL(url)

    message.success('对话记录导出成功！')
    handleCancel()
  } catch (error) {
    console.error('导出对话记录失败：', error)
    message.error('导出对话记录失败，请稍后重试')
  } finally {
    exporting.value = false
  }
}

// 取消导出
const handleCancel = () => {
  visible.value = false
  // 重置表单
  exportForm.startTime = undefined
  exportForm.endTime = undefined
}
</script>

<style scoped>
.export-form {
  padding: 8px 0;
}

.export-form label {
  font-weight: 500;
  color: #262626;
}
</style>
